# -*- coding: utf-8 -*-
import os
import Image, ImageFont, ImageDraw
import pprint
import logging
import re
import datetime
import workerpool
import traceback
import math
from pymongo import Connection
from wlib import *

BG_160_200 = 'Icons/tygia_bg_2x1.png'
GOLD_ICON = 'Icons/gold.png' 
FONT = 'Font/verdana.ttf'
FONTB = 'Font/verdanab.ttf'
OUTPUT = 'Output'

class Generator():
    
    def __init__(self, host, port):
        try:
            self.connection = Connection(host, port)
        except:
            logger.error(unicode('Không kết nối được tới database server', 'utf-8'))
        self.dBName = 'giavang'
        
    def __del__(self):
        self.connection.end_request()
    
    def getFont(self, size=13):
        return ImageFont.truetype(filename=FONT, size=size)
    
    def getFontBold(self, size=14):
        return ImageFont.truetype(filename=FONTB, size=size)
    
    def drawText(self, im, text, xy=(0,0), size=13, color=(255,255,255), type='normal', align=None, valign=None, margin=(0,0,0,0)):
        if im == None: return
        im_w, im_h = im.size
        if type == 'bold':
            font = self.getFontBold(size)
        else:
            font = self.getFont(size)
        t_w, t_h = font.getsize(text)
        if align != None:
            x, y = xy
            if align == 'left':
                xy = (0, y)
            elif align == 'center':
                xy = (im_w/2 - t_w/2, y)
            elif align == 'right':
                xy = (im_w-t_w, y)
        if valign != None:
            x, y = xy
            if valign == 'top':
                xy = (x, 0)
            elif valign == 'middle':
                xy = (x, im_h/2 - t_h/2)
            elif valign == 'bottom':
                xy = (x, im_h-t_h)
        mtop, mright, mbottom, mleft = margin
        dy = mtop - mbottom
        dx = mleft - mright
        if dy < 0:
            xy = (xy[0], xy[1] + dy)
        elif dy > 0:
            xy = (xy[0], xy[1] - dy)
        if dx < 0:
            xy = (xy[0] + dx, xy[1])
        elif dx > 0:
            xy = (xy[0] - dx, xy[1])
        draw = ImageDraw.Draw(im)
        draw.text(xy, text, font=font, fill=color)
        del draw
    
    def getData(self):
        logger.debug('call getData')
        data = []
        try:
            db = self.connection[self.dBName]
            collection = db['sjc']
            row = collection.find().sort('lastupdate', -1).limit(1)
            dcities = {'Hà Nội': 'HN', 'TPHCM': 'HCM', 'Nha Trang': 'NTrang'}
            cities = ['Hà Nội', 'TPHCM', 'Nha Trang', 'Đà Nẵng', 'Cần Thơ']
            types = ['Vàng SJC', 'Vàng SJC 1L']
            if row:
                for city in cities:
                    for item in row[0]['data']:
                        if (item['thanhpho'] == city) and (item['loai'] in types):
                            data.append(item)
        except:
            logger.error(traceback.format_exc())
        return data
    
    def process(self):
        data = self.getData()
        self.size2x1(data)
    
    def size2x1(self, data, limit=3):
        logger.debug('call process')
        try:
            im = Image.open(BG_160_200)
            i = 0
            wicon = Image.open(GOLD_ICON)
            wicon = wicon.resize((12, 12))
            wicon = wicon.convert("RGBA")
            r,g,b,a = wicon.split()
            for item in data:
                xy = (5, i*30)
                im.paste(wicon, (xy[0], xy[1]+3), mask=a)
                self.drawText(im, text=item['thanhpho'], xy=(xy[0]+15, xy[1]), type='bold')
                self.drawText(im, text=item['mua'], xy=(xy[0]+15, xy[1]+15))
                self.drawText(im, text=item['ban'], xy=(xy[0]+85, xy[1]+15))
                i += 1
                if i >= limit: break
            im.save('{0}/giavang_wg2x1.png'.format(OUTPUT))
        except:
            logger.error(traceback.format_exc())
        
if __name__ == '__main__':
    fmt = "%(levelname)-6s - %(asctime)s - %(lineno)-3s - %(msg)s"
    logging.basicConfig(format=fmt)
    logger = logging.getLogger('currency_generator')
    logger.setLevel(logging.DEBUG)
    logger.debug('start currency image generating')
    try:
        w = Generator('beta.mana.vn', 27017)
        w.process()
    except:
        logger.error(traceback.format_exc())
    logger.debug('finished currency image generating at {0}'.format(datetime.datetime.now()))
    os._exit(1)
    
    
    
    